'''
Created on 18.10.2012

@author: doleynik
'''
import time
import json

import webapp2
from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, expenditure

from common import functions

from wtforms.ext.appengine.db import model_form
from wtforms.fields import TextField
from wtforms import validators

from BaseHandler import BaseHandler

class Expenditures(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Expenditures, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'type': _('Type'), 'code': _('Nature code'), 'title': _('Title'), 'TVA': _('VAT Rate (%)'),
                       'deduc': _('Deduction rate (%)'), 'reduc': _('Recoverable rate (%)'),
                       'regroupe': _('Regroup'), 'direction': _('Direction'), 'subaccount': _('Account')
                       }

    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))

        template_values = {
            'title': _('Expenditures'),
            'header': _('%s. Expenditures' % imm.name),
            'immeuble': imm,
            'app_user': self.au,
            'lurl': users.create_logout_url('/'),
            'section': 'parametrage',
            'leftmenu': 'expenditures',
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/expenditures.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))

        exp = []
        exp_list = imm.get_exp_list()
        for et in imm.expenditure_type_set.run():
            exp.append(['exp_type', unicode(et.code), unicode(et.name), '', '', '', '', '', str(et.key())])
            for e in exp_list:
                if e.type.key() == et.key():
                    exp.append(['exp',
                                e.code,
                                e.title,
                                e.reduc,
                                e.deduc, 
                                str(e.subaccount),
                                e.direction,
                                e.TVA.value, 
                                str(e.key().name())
                                ])
        ret = {}
        ret['aaData'] = exp
        self.response.out.write(json.dumps(ret))
    
    def op_list_names_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))

        expenditures = imm.get_exp_list()
        exp = []
        for e in expenditures:
            exp.append(str(e))
        self.response.out.write(json.dumps(exp))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        subaccts = imm.get_subacc_list()
        
        ExpForm = model_form(expenditure, exclude=['lastchange_by'])
        setattr(ExpForm, 'subaccount', TextField(u'Debit account', [validators.required(),]))
        ExpForm.type.creation_counter = 1
        ExpForm.code.creation_counter = 2
        ExpForm.title.creation_counter = 3
        ExpForm.TVA.creation_counter = 4
        ExpForm.deduc.creation_counter = 5
        ExpForm.reduc.creation_counter = 6
        ExpForm.regroupe.creation_counter = 7
        ExpForm.direction.creation_counter = 8
        ExpForm.subaccount.creation_counter = 9
        
        if self.request.method == 'GET':
            form = ExpForm()
            form['type'].query = imm.expenditure_type_set
        
        if self.request.method == 'POST':
            post_obj = self.request.POST
            
            exists = False
            for a in subaccts:
                name = str(a.code) + ' ' + str(a.name)
                if name == post_obj['subaccount']:
                    post_obj['subaccount'] = a
                    exists = True
                    break
            if exists is False:
                post_obj['subaccount'] = ''
            
            form = ExpForm(post_obj)
            
            form['type'].query = imm.expenditure_type_set
            
            if form.validate():
                new_exp =  expenditure( key_name = form['code'].data + '_' + str(imm.key().id()),
                                        type = form['type'].data,
                                        code=form['code'].data, 
                                        title=form['title'].data,
                                        TVA = form['TVA'].data,
                                        deduc = form['deduc'].data,
                                        reduc = form['reduc'].data,
                                        regroupe = form['regroupe'].data,
                                        subaccount = form['subaccount'].data,
                                        lastchange_by=self.au )
                new_exp.put()
                while not new_exp.is_saved():
                    time.sleep(2)
                ok_message = _('Expenditure was added.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))

    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        exp_id = kwargs.get('exp_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        exp = expenditure.get_by_key_name(exp_id)
        subaccts = imm.get_subacc_list()
        
        ExpForm = model_form(expenditure, exclude=['lastchange_by'])
        setattr(ExpForm, 'subaccount', TextField(u'Debit account', [validators.required(),]))
        ExpForm.type.creation_counter = 1
        ExpForm.code.creation_counter = 2
        ExpForm.title.creation_counter = 3
        ExpForm.TVA.creation_counter = 4
        ExpForm.deduc.creation_counter = 5
        ExpForm.reduc.creation_counter = 6
        ExpForm.regroupe.creation_counter = 7
        ExpForm.direction.creation_counter = 8
        ExpForm.subaccount.creation_counter = 9
        
        if self.request.method == 'GET':
            form = ExpForm(obj=exp)
            form['type'].query = imm.expenditure_type_set
        
        if self.request.method == 'POST':
            post_obj = self.request.POST
            
            exists = False
            for a in subaccts:
                name = str(a.code) + ' ' + str(a.name)
                if name == post_obj['subaccount']:
                    post_obj['subaccount'] = a
                    exists = True
                    break
            if exists is False:
                post_obj['subaccount'] = ''
            
            form = ExpForm(post_obj)
            
            form['type'].query = imm.expenditure_type_set
            
            if form.validate():
                exp.type = form['type'].data
                exp.code=form['code'].data 
                exp.title=form['title'].data
                exp.TVA = form['TVA'].data
                exp.deduc = form['deduc'].data
                exp.reduc = form['reduc'].data
                exp.regroupe = form['regroupe'].data
                exp.subaccount = form['subaccount'].data
                exp.lastchange_by=self.au
                exp.put()
                ok_message = _('Expenditure was changed.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    

    def op_predefine(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        expenditures_template = imm.get_prdefine_template("expenditures") 
        
        if self.request.method == 'POST':
            imm.set_predefine_expenditures(self.au)
            self.redirect(webapp2.uri_for('parametrage_nature_des_depenses', imm_id=imm_id, command='list'))
            return
        
        template_values = {
            'title': _('Expenditures template'),
            'header': _('Set of expenditures'),
            'immeuble': imm,
            'table': expenditures_template,
            'app_user': self.au,
            'lurl': users.create_logout_url('/'),
            'section': 'parametrage',
            'fields': self.fields
            }
        
        template = self.jinja2.get_template('templates/expenditures_predefine.html')
        self.response.out.write(template.render(template_values))
    
    def op_calc_vat_charge_deduction(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ret = {"vat_value": 0.0, "rental_charges": 0.0, "tax_deduction": 0.0}
        exp_name = self.request.GET.get('expenditure', None)
        if exp_name is None:
            self.response.out.write(json.dumps(ret))
            return
        
        amount = self.request.GET.get('amount', None)
        try:
            amount = float(amount)
        except:
            self.response.out.write(json.dumps(ret))
            return
        
        exp_id = None
        exp_list = imm.get_exp_list()
        for e in exp_list:
            if str(e) == exp_name:
                exp_id = e.key()
        
        if exp_id is None:
            self.response.out.write(json.dumps(ret))
            return
        
        exp = expenditure.get(exp_id)
        if not exp:
            self.response.out.write(json.dumps(ret))
            return
        
        vat = exp.TVA.value
        vat_value = round(amount - (amount/(1.0 + vat/100.0)), 2)
        rental_charges = round(amount * (exp.reduc/100.0), 2)
        tax_deduction = round(amount * (exp.deduc/100.0), 2)
        
        ret = {"vat_value": vat_value, "rental_charges": rental_charges, "tax_deduction": tax_deduction}
        self.response.out.write(json.dumps(ret))
        